package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }
    @Autowired
    private IElderService elderService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInService checkInService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //入住申请，首先检查老人是否已入住
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        Elder oldElder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, idCardNo)
                .one();
        //如果已经存在，直接返回
        if (oldElder != null&&  oldElder.getStatus() == 1) {
            throw new BaseException("该老人已入住");
        }
        //更新床位状态
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed oldBed = bedService.selectBedById(bedId);
        if (oldBed == null) {
            throw new BaseException("床位不存在");
        }
        oldBed.setBedStatus(1);
        bedService.updateById(oldBed);
        //新增或更新老人
        Elder elder = BeanUtil.toBean(checkInApplyDto.getCheckInElderDto(), Elder.class);
        if(oldElder!=null){
            elder.setId(oldElder.getId());
        }
        elder.setStatus(1);
        elder.setBedId(bedId);
        elder.setBedNumber(oldBed.getBedNumber());
        elderService.saveOrUpdate(elder);
        //新增签约办理
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(oldBed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkInService.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
    }
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        CheckIn checkIn = getById(id);
        if(checkIn==null){
            throw new BaseException("入住信息不存在");
        }
        String json = checkIn.getRemark();
        vo.setElderFamilyVoList(JSONUtil.toList(json, ElderFamilyVo.class));
        Long elderId = checkIn.getElderId();
        Elder elder = elderService.getById(elderId);
        if(elder==null){
            throw new BaseException("老人不存在");
        }
        Contract contract = contractService.lambdaQuery()
                .eq(Contract::getElderId, elder.getId())
                .one();
        vo.setContract(contract);
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        vo.setCheckInElderVo(checkInElderVo);
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId())
                .one();
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getEndDate());
        checkInConfigVo.setEndDate(checkIn.getStartDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        vo.setCheckInConfigVo(checkInConfigVo);
        return vo;
    }
}
